package com.hongli.blog.scheduledtask;

import com.hongli.blog.config.CookieUtils;
import com.hongli.blog.config.Result;
import com.hongli.blog.controller.LoginController;
import com.hongli.blog.entity.*;
import com.hongli.blog.mapper.*;
import com.hongli.blog.redisconfig.RedisUtil;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/** 初始化控制器
 * @Author ZERO
 * @Date 2021/11/8 16:29
 **/
@RestController
public class InitializationController {

    @Autowired
    private Usermapper usermapper;

    @Autowired
    private Rolemapper rolemapper;

    @Autowired
    private Basicsmapper basicsmapper;

    @Autowired
    private Authoritymapper authoritymapper;

    @Autowired
    private RoleAuthoritymapper roleAuthoritymapper;

    @Autowired
    private RedisUtil redisUtil;

    private final String V = "前台";
    private final String J = "后台";

    /** 获取当前时间
      * @author ZERO
      * @date 2021/11/8 17:53
    **/
    public Date Processing_Time(){
        Date times = null;
        try{
            SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetimes = SDF.format(new Date());
            times = SDF.parse(datetimes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return times;
    }

    /** 处理时间返回前面
      * @author ZERO
      * @date 2021/11/12 14:57
    **/
    public String Times(Date now){
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String DealWithTimes = ft.format(now);
        return DealWithTimes;
    }

    /** md5 加密与解密（已使用springboot自带的md5）
      * @author ZERO
      * @date 2021/11/16 14:29
    **/
    public String MD5_Encrypt(String pass){
        // 生成盐,默认长度 16 位
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        // 设置 hash 算法迭代次数
        int times = 2;
        // 得到 hash 后的密码
        return new SimpleHash("md5",pass,salt,times).toString();
    }

    /** 获取cookie后的redis
      * @author ZERO
      * @date 2021/11/17 15:09
    **/
    public int Cookie_Decryption(HttpServletRequest request){
        //cookie(a1,a2) ==> redis(a2,a3)
        try{
            String S = CookieUtils.getCookie(request,new LoginController().COOKIE_BLOG).trim();
            if(S == null || "".equals(S)){
                return 0;
            }
            if(redisUtil.hasKey(S)){
                UserDao userDao = usermapper.SelectUserName(Integer.parseInt(redisUtil.get(S).trim()));
                if(userDao == null) return 0;
                return userDao.getUserid();
            }else return 0;
        }catch (Exception e){
            return 0;
        }
    }

    /** 初始化SQL数据
      * @author ZERO
      * @date 2021/11/8 16:40
    **/
    @PostConstruct
    public void InitializationSQLdata(){
        //第一：角色
        RoleDao roledao = rolemapper.SelectRoleAdmin();
        RoleDao roleData = new RoleDao(0,"管理员","1");
        if(roledao == null){
            rolemapper.InsertRole(roleData);
        }else if(!"1".equals(roledao.getRoleenableNo())){
            rolemapper.UpdataRoleNO(roledao.getRoleid(),"1");
        }

        //第二：权限
        AuthorityDao authorV = authoritymapper.SelectAuthorityName(V);
        AuthorityDao authorJ = authoritymapper.SelectAuthorityName(J);
        if(authorV == null){
            authoritymapper.InsertAuthority(V,0);
        }
        if(authorJ == null){
            authoritymapper.InsertAuthority(J,0);
        }

        //第三：角色权限
        RoleAuthorityDao roleauthorV = roleAuthoritymapper.SelectRoleAuthorityVJ(V);
        RoleAuthorityDao roleauthorJ = roleAuthoritymapper.SelectRoleAuthorityVJ(J);
        if(roleauthorV == null){
            roleAuthoritymapper.InsertRoleAuthority(rolemapper.SelectRoleAdmin().getRoleid(),authoritymapper.SelectAuthorityName(V).getAuthorityid());
        }
        if(roleauthorJ == null){
            roleAuthoritymapper.InsertRoleAuthority(rolemapper.SelectRoleAdmin().getRoleid(),authoritymapper.SelectAuthorityName(J).getAuthorityid());
        }

        //第四：用户
        String pass = DigestUtils.md5DigestAsHex("1234567890".getBytes());
        List<UserDao> user = usermapper.SelectUserRole();
        if(user.size() <= 0){
            RoleAuthorityDao roleiddata = roleAuthoritymapper.SelectRoleAuthorityVJ(V);
            UserDao userData = new UserDao(0,roleiddata.getRoleid(),"大象",pass,"1",Processing_Time(),"1");
            usermapper.Insertuser(userData);
        }

        //第五：基础数据
        List<BasicsDao> listbasicsall = basicsmapper.SelectAllBasics();
        if(listbasicsall.size() <= 0){
            basicsmapper.InsertBasics(
                    new BasicsDao(0,"第一套","零散的星光","月亮下的月光",Processing_Time(),"粤ICP备2021110902","1"));
        }
    }
}
